<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body,html {
            margin: 0;

        }

        #waterFull{
            width: 800px;
            margin: 0 auto;
            display: flex;
            justify-content: center;
        }
        .item {
            flex-basis: 20%;
        }
        img{
            width: 100%;
            height: auto;
            display: block;
        }
    </style>
</head>
<body>
    <div id="waterFull">
        <div class="item">
            <div id="box1">
                <img src="./imgs/2.jpg" alt="">
            </div>
        </div>
        <div class="item">
            <div id="box2"><img src="./imgs/1.jpg" alt=""></div>
        </div>
        <div class="item">
            <div id="box3">
                <img src="./imgs/5.jpg" alt="">
            </div>
        </div>
        <div class="item">
            <div id="box4">
                <img src="./imgs/3.jpg" alt="">
            </div>
        </div>
        <div class="item">
            <div id="box5"><img src="./imgs/4.jpg" alt=""></div>
        </div>
    </div>
    <script>
        window.onload = function() {
            var timer // 定时器
            // 图片的集合
            const imgs = ['./imgs/2.jpg', './imgs/1.jpg', './imgs/3.jpg', './imgs/4.jpg', './imgs/5.jpg']
            // 获取所有的列的盒子
            let lists = document.getElementsByClassName('item')
            // 将元素转化为数组
            lists = Array.from(lists)
            // 获取屏幕高度
            let cHeight = document.documentElement.clientHeight
            
            function waterFull() {
                // 准备一个数据 收集元素信息 并准备排序
                let arr = []
                lists.forEach(item => {
                    var el = item.getElementsByTagName('div')[0]
                
                    var obj = {
                        el: el,
                        height: el.offsetHeight
                    }

                    // console.log(obj)
                    arr.push(obj)
                })

                arr.sort((a, b) => {
                    return a.height - b.height
                })
                // 随机选择一张图片 准备加入瀑布流
                function randomImg() {
                    return imgs[Math.round(Math.random()*4)] 
                }
                if(arr[0].height > cHeight) {
                    clearInterval(timer)
                }

                let img = `<img src=${randomImg()} />`

                arr[0].el.insertAdjacentHTML('beforeEnd', img)
            }
            timer = setInterval(() => {
                waterFull()
            }, 300);


            window.addEventListener('scroll', function() {
                waterFull()
            })
        }
    </script>
</body>
</html>